<?php

namespace Addons\WXCoupon\Controller;
use Home\Controller\AddonsController;

class WXCouponController extends AddonsController{
    /*上传logo*/
    public function postlogo(){
//        $data = array('buffer' => "@D:\logo.png");
//        $res = JsonPost('https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=mTfjB52UE0mgkl0Amei3p1Nvm0Xl4P99jE37f2LltL5o2N4xoDtBKal-aAXnL5dnCt86hKwfkCl4SZHrqEfJdDLIV5rsx504fkeu1glQv48', $data);
//        dump(json_decode($res));
        $addon_class = get_addon_class (_ADDONS);
        $data = new $addon_class ();
        $addon ['config'] = include $data->config_file;
        dump($addon ['config']['logourl']);
        $this->display();
    }

    /*上传门店*/
    public function postmdlist(){
        $map['com_md_type01'] = array('neq', 4);
        $res = M('com_md')
            ->table('wp_com_md md')
            ->join('wp_com_area area ON md.com_area_code = area.com_area_code')
            ->field('\'东莞国药\' as business_name, com_zip_name as branch_name, \'广东省\' as province, \'东莞市\' as city, com_area_name as district, com_md_add as address, com_md_tel as telephone, \'连锁药房\' as category, com_md_long as longitude, com_md_lat as latitude')
            ->where('com_md_add is not null and com_md_long is not null and com_md_long <> \'\'')
            ->select();
        foreach($res as $key => &$val){
            $txpoint = $this->detailbdpoint($val['longitude'], $val['latitude']);
            $val['longitude'] = $txpoint['longitude'];
            $val['latitude'] = $txpoint['latitude'];
            $val['business_name'] = urlencode($val['business_name']);
            $val['branch_name'] = urlencode($val['branch_name']);
            $val['province'] = urlencode($val['province']);
            $val['city'] = urlencode($val['city']);
            $val['district'] = urlencode($val['district']);
            $val['address'] = urlencode($val['address']);
            $val['category'] = urlencode($val['category']);
        }
        unset($val);
        $postdata = urldecode(json_encode(array("location_list"=>$res)));
        $token = get_token();
        $access_token = get_access_token($token);
        $url = 'https://api.weixin.qq.com/card/location/batchadd?access_token=' . $access_token;
//        $export = JSONPost($url, $postdata);
//        $this->ajaxReturn(json_decode($export, true));
    }

    /*百度经纬度转腾讯经纬度*/
    public function detailbdpoint($lng,$lat){
        $res = JsonGet('http://apic.map.qq.com/translate/?type=3&points=' . $lng . ',' . $lat . '&output=jsonp&pf=jsapi');
        $resarr = json_decode($res, true);
        return array('longitude'=>$resarr['detail']['points'][0]['lng'], 'latitude'=>$resarr['detail']['points'][0]['lat']);
    }

    /*拉取门店*/
    public function getmdlist(){
        $token = get_token();
        $access_token = get_access_token($token);
        $data = json_encode(array('offset'=>0, 'count'=>1));
        $url = 'https://api.weixin.qq.com/card/location/batchget?access_token=' . $access_token;
        $res = JsonPost($url, $data);
        $resarr = json_decode($res, true);
        $this->ajaxReturn($resarr);
    }

    /*获取颜色列表*/
    public function colorlist(){
        $token = get_token();
        $access_token = get_access_token($token);
        $url = 'https://api.weixin.qq.com/card/getcolors?access_token=' . $access_token;
        $res = JsonGet($url);
        $resarr = json_decode($res, true);
        $this->assign('colors', $resarr['colors']);
        $this->display();
    }

    /*创建卡券*/
    public function createWXCoupon(){

    }

    /*创建测试用户白名单*/
    public function createtestwhitelist(){
        $token = get_token();
        $access_token = get_access_token($token);
        $url = 'https://api.weixin.qq.com/card/testwhitelist/set?access_token=' . $access_token;
        $data = array('username'=>array('skhero102','gongxianchao1982','wuwei494800','heby281','xu-zhi-hong','fuyuehuman','l1749111790'));
        $res = JsonPost($url, json_encode($data));
        $resarr = json_decode($res);
        $this->ajaxReturn($resarr);
    }

    /*查询卡券列表*/
    public function batchget(){
        $token = get_token();
        $access_token = get_access_token($token);
        $url = 'https://api.weixin.qq.com/card/batchget?access_token=' . $access_token;
        $data = array('offset'=>0, 'count'=>50);
        $res = JsonPost($url, json_encode($data));
        $resarr = json_decode($res, true);
        return $resarr['card_id_list'];
//        $this->ajaxReturn($resarr);
    }
    /*查询卡券详情*/
    public function getcardinfo($cid = NULL){
        if ($cid !== NULL) {
            $cardid = $cid;
        } elseif (! empty ( $_REQUEST ['cardid'] )) {
            $cardid = $_REQUEST ['cardid'];
        }
        $token = get_token();
        $access_token = get_access_token($token);
        $url = 'https://api.weixin.qq.com/card/get?access_token=' . $access_token;
        $data = array('card_id'=>$cardid);
        $res = JsonPost($url, json_encode($data));
        $resarr = json_decode($res, true);
        return $resarr['card'];
//        $this->ajaxReturn($resarr);
    }
    /*获取页面卡卷渲染*/
    public function getcardlist(){
        $listarr = array();
        $cardlist = $this->batchget();
        foreach($cardlist as $cardid){
            $carddetail = $this->getcardinfo($cardid);
            $cardtypestr = strtolower($carddetail['card_type']);
            $cardstatus = $carddetail[$cardtypestr]['base_info']['status'];
            $quantity = $carddetail[$cardtypestr]['base_info']['sku']['quantity'];
            if($cardstatus != 'CARD_STATUS_NOT_VERIFY' && $cardstatus !='CARD_STATUS_VERIFY_FALL' && $cardstatus !='CARD_STATUS_DELETE' && $quantity>0){
                $cardtype = '';
                $wxcouponinfo = getWXCouponInfo($cardid);
                switch($carddetail['card_type']){
                    case 'GENERAL_COUPON':
                        $cardtype = '通用券';
                        break;
                    case 'GROUPON':
                        $cardtype = '团购券';
                        break;
                    case 'DISCOUNT':
                        $cardtype = '折扣券';
                        break;
                    case 'GIFT':
                        $cardtype = '礼品券';
                        break;
                    case 'CASH':
                        $cardtype = '代金券';
                        break;
                    case 'MEMBER_CARD':
                        $cardtype = '会员卡';
                        break;
                    case 'SCENIC_TICKET':
                        $cardtype = '门票';
                        break;
                    case 'MOVIE_TICKET':
                        $cardtype = '电影票';
                        break;
                    case 'BOARDING_PASS':
                        $cardtype = '飞机票';
                        break;
                    case 'LUCKY_MONEY':
                        $cardtype = '红包';
                        break;
                    case 'MEETING_TICKET':
                        $cardtype = '会议门票';
                        break;
                }
                $cardinfo = array(
                    'id'=>$cardid,
                    'timestamp'=>$wxcouponinfo['timestamp'],
                    'signature'=>$wxcouponinfo['signature'],
                    'card_type'=>$cardtype,
                    'brand_name'=>$carddetail[$cardtypestr]['base_info']['brand_name'],
                    'sub_title'=>$carddetail[$cardtypestr]['base_info']['sub_title'],
                    'reduce_cost'=>$carddetail[$cardtypestr]['reduce_cost']/100,
                    'color'=>$carddetail[$cardtypestr]['base_info']['color'],
                    'fixed_term'=>$carddetail[$cardtypestr]['base_info']['date_info']['fixed_term']
                );
                $listarr[] = $cardinfo;
            }
        }
        return $listarr;
//        $this->ajaxReturn($listarr);
    }

    /*领取卡券页面*/
    public function couponlist(){
        $map['uid'] = $this->mid;
        $res = M('card_member')->where($map)->find();
        if(!$res){
            redirect ( addons_url ( 'Card://Card/show' ) );
        }
        else{
            $couponlist = $this->getcardlist();
            foreach($couponlist as &$coupon){
                if($coupon['id'] == 'pUOAMt639xrt2ax5RJmAFpChHyC0'){
                    $coupon['sub_title'] = '厚街各分店使用';
                }
                else if($coupon['id'] == 'pUOAMt_nse3dQx30LOpuiSh_4SfY'){
                    $coupon['sub_title'] = '限常平、东坑、谢岗、寮步、沙田各分店使用';
                }
            }
            unset($coupon);
            $this->assign('couponlist', $couponlist);
            $this->display();
        }
    }

    /*门店登录页初始化*/
    public function adminlogin(){
        $adminlist = M('admininfo_ctrl')->field('id, name')->select();
//        $areacode = I('areacode');
//        $flist = M ( 'com_area' )->field('com_area_code as code, com_area_name as name')->select();
//        if($flist){
//            $mdmap['com_area_code'] = $areacode;
//            $mlist = M ( 'com_md' )->field('com_md_code as code, com_zip_name as name')->where($mdmap)->select();
//        }
//        $tourl = I('tourl');
//        if($tourl){
//            $this->assign ( 'tourl', $tourl );
//        }
        $this->assign ( 'login_id', 1 );
        $this->assign ( 'adminlist', $adminlist );
        $this->display();
    }

    /*门店登录*/
    public function admintologin(){
        $map['id'] = I('loginid');
        $adminpwd = I('adminpwd');
        $sadminpwd = M('admininfo_ctrl')->where($map)->getField('password');
        if($adminpwd == $sadminpwd){
            session('login_id', $map['id']);
            $this->ajaxReturn(array('statu'=>0, 'content'=>'登录成功!'));
        }
        else{
            session('login_id', null);
            $this->ajaxReturn(array('statu'=>1, 'content'=>'登录失败!'));
        }
    }

    /*sn码核销*/
    public function tosnconsume(){
        $msg = array('statu'=>0, 'content'=>'');
        $code = I('code');
        $token = get_token();
        $data = array('code'=>$code);

        $map['token'] = $token;
        $map['sn'] = $code;
        $map['is_use'] = 0;
        $map['status'] = 1;
        $res = M('sn_code')->where($map)->find();
        $smdcode = session('gy_mdcode');
        if(empty($smdcode)){
            $msg['statu'] = 1;
            $msg['content'] = '登录超时，请刷新页面!';
        }
        else if($res){
            $sncodetime = M(strtolower($res['addon']))->where(array('id'=>$res['target_id']))->getField('sncodetime');
            $time = time();
            if($sncodetime > $time){
                $newdata['is_use'] = 1;
                $newdata['use_time'] = $time;
                $result = M('sn_code')->where($map)->save($newdata);

                /*查询奖品详细*/
                $prizemap['id'] = $res['prize_id'];
                $prizename = M('prize')->where($prizemap)->getField('name');
                $msg['content'] = '已核销成功! 奖品:' . $prizename;

                /*新增门店SN码核销记录*/
                $logdata['sncode'] = $code;
                $logdata['consumetime'] = $time;
                $logdata['com_md_code'] = session('gy_mdcode');
                M('sn_code_log')->add($logdata);
            }
            else{
                $msg['statu'] = 1;
                $msg['content'] = '核销时限已过';
            }
        }
        else{
            $msg['statu'] = 1;
            $msg['content'] = 'SN码未找到或已核销!';
        }
        $this->ajaxReturn($msg);
    }

    /*门店核销统计*/
    public function mdconsumeview(){
        $msg = array();
        $result = M('yhcard_log')
            ->table('wp_yhcard_log log')
            ->join('wp_yhcard_info info ON info.cardid = log.cardid')
            ->field('info.cardid as cardid, cardname')
            ->group('cardid')
            ->select();
        foreach($result as $carditem){
            $res = M('yhcard_log')
                ->table('wp_yhcard_log log')
                ->join('wp_com_md md ON md.com_md_code = log.com_md_code')
                ->field('md.com_md_code as mdcode, com_zip_name as mdname, count(cardcode) as consumecount')
                ->where(array('cardid'=>$carditem['cardid']))
                ->group('md.com_md_code')
                ->order('consumecount desc')
                ->select();
            $carditem['info'] = $res;
            $msg[] = $carditem;
        }
        $this->assign('cardlist', $msg);
        $this->display();
    }
    /*门店SN码核销查询*/
    public function showsnresult(){
        $this->display();
    }
    /*门店SN码核销查询*/
    public function getmdsninfo(){
        $mdcode = I('mdcode');
        $mdname = M('com_md')->where(array('com_md_code'=>$mdcode))->getField('com_zip_name');
        $targetid = I('targetid');
        $result = M('sn_code_log')
            ->table('wp_sn_code_log log')
            ->join('wp_sn_code code ON code.sn = log.sncode')
            ->where(array('com_md_code'=>$mdcode,'target_id'=>$targetid))
//            ->join('com_md md ON md.com_md_code = log.com_md_code')
            ->field('count(code.prize_id) as prizenum, code.prize_title as prizetitle')
            ->group('code.prize_id')
            ->select();
        $this->ajaxReturn(array('name'=>$mdname, 'content'=>$result));
    }
    /*按奖品查询各门店数量*/
    public function showprizesresult(){
        $this->display();
    }
    public function getprizeslist(){
        $map['target_id'] = I('targetid');
        $map['addon'] = I('addontype');
        $res = M('prize')->field('id, title, num')->where($map)->select();
        $this->ajaxReturn($res);
    }
    public function getprizeinfo(){
        $map1['id'] = I('prizeid');
        $map1['target_id'] = I('targetid');
        $map1['addon'] = I('addontype');
        $prizenum = M('prize')->where($map1)->getField('num');
        $prizelist = M('sn_code_log')
            ->table('wp_sn_code_log log')
            ->join('wp_com_md md ON md.com_md_code = log.com_md_code')
            ->join('wp_sn_code code ON code.sn = log.sncode')
            ->field('md.com_zip_name as mdname, count(code.prize_id) as sumprize')
            ->where('code.prize_id = ' . $map1['id'] . ' and code.target_id = ' . $map1['target_id'] . ' and code.addon = "' . $map1['addon'] . '"')
            ->group('log.com_md_code')
            ->select();

        $map2['prize_id'] = I('prizeid');
        $map2['target_id'] = I('targetid');
        $map2['addon'] = I('addontype');
        $winres = M('sn_code')->field('count(prize_id) as winnum')->where($map2)->find();
        $this->ajaxReturn(array('num'=>$prizenum, 'winnum'=>$winres['winnum'], 'list'=>$prizelist));
    }

    public function test(){
//        $cardid = 'pUOAMt96Jq8eZULN32UOoefp0dJQ';
//        $res = getWXCouponInfo($cardid);
//        $this->ajaxReturn($res);
    }

    /*下载SN码核销记录*/
    function downprizeinfo(){
        $map1['id'] = I('prizeid');
        $map1['target_id'] = I('targetid');
        $map1['addon'] = I('addontype');
        $comjc = I('com_jc');
        $prizelist = M('sn_code_log')
            ->table('wp_sn_code_log log')
            ->join('wp_com_md md ON md.com_md_code = log.com_md_code')
            ->join('wp_sn_code code ON code.sn = log.sncode')
            ->field('md.com_zip_name as mdname, count(code.prize_id) as sumprize')
            ->where('code.prize_id = ' . $map1['id'] . ' and code.target_id = ' . $map1['target_id'] . ' and md.com_jc = "' . $comjc . '" and code.addon = "' . $map1['addon'] . '"')
            ->group('log.com_md_code')
            ->select();
        $prizename = M('prize')->where(array('id'=>$map1['id']))->getField('name');
        $str = "门店名称,核销数量\n";
        $str = iconv('utf-8','gb2312',$str);
        foreach($prizelist as $row){
            $mdname = iconv('utf-8','gb2312',$row['mdname']);
            $sumprize = $row['sumprize'];
            $str .= $mdname.",".$sumprize."\n"; //用引文逗号分开
        }
        $filename = $comjc . '-' . $prizename . '.csv'; //设置文件名
        $this->export_csv($filename, $str); //导出
        exit;
//        $this->ajaxReturn(array('prizelist'=>$prizelist, 'prizename'=>$prizename, 'addon'=>$map1['addon']));
    }
    function export_csv($filename,$data) {
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo $data;

    }
}
